package com.example.demoserver.controller;

import com.example.demoserver.entity.GetMessage;
import com.example.demoserver.entity.TrainQuestions;
import com.example.demoserver.entity.TrainUserquesions;
import com.example.demoserver.service.TrainQueoptionsService;
import com.example.demoserver.service.TrainQuestionsService;
import com.example.demoserver.service.TrainUserquesionsService;
import com.example.demoserver.service.impl.PollingService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Component
public class UserController {
    @Value("${examServer.ip}")
    private String ip;
    @Value("${examServer.port}")
    private String port;
    @Value("${app.name}")
    private String name;
    private final PollingService pollingService;
    private final TrainUserquesionsService trainUserquesionsService;
    private final TrainQuestionsService trainQuestionsService;
    private final TrainQueoptionsService trainQueoptionsService;
    @GetMapping("/login")
    public String login(String username, String password, Integer type, HttpServletResponse response1) {
        Map<String, Object> map = new HashMap<>();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("http://" + ip + ":" + port + "/user/login?username=" + username + "&password=" + password + "&type=" + type);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    ObjectMapper objectMapper1 = new ObjectMapper();
                    // 将JSON字符串转换为Map
                    JsonNode rootNode1 = objectMapper1.readValue(result, JsonNode.class);
                    Cookie cookie = new Cookie(name + "-token", rootNode1.get("token").asText().split(",")[1]);
                    cookie.setPath("/");
                    cookie.setHttpOnly(true);
                    response1.addCookie(cookie);
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/save")
    public String savaOne(Integer userId, HttpServletRequest request) {
        TrainUserquesions trainUserquesions1=trainUserquesionsService.select();
        TrainUserquesions trainUserquesions = new TrainUserquesions();
        trainUserquesions.setUserid(userId);
        trainUserquesions.setSavetime(Util.getNowTime());
        trainUserquesions.setSaveversion(0);
        trainUserquesions.setQuestionids("");
        Cookie[] cookies = request.getCookies();
        String token="";
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ((name+"-token").equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }
        trainUserquesions.setToken(token);
        if(trainUserquesions1==null){
            trainUserquesionsService.save(trainUserquesions);
        }else{
            if(trainUserquesions1.getUserid()!=userId){
                trainQuestionsService.deleteAll();
                trainQueoptionsService.deleteAll();
                trainUserquesionsService.deleteAll();
                trainUserquesionsService.save(trainUserquesions);
            }
        }
        return "200";
    }

}
